package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/tencentyun/cos-go-sdk-v5"
)

type TestController struct{}

// 临时凭证信息结构体
type TempAuthInfo struct {
	TmpSecretID  string `json:"TmpSecretId"`
	TmpSecretKey string `json:"TmpSecretKey"`
	Token        string `json:"Token"`
	ExpiredTime  int64  `json:"ExpiredTime"` // 使用 Unix 时间戳
}

func (ctrl *TestController) TestShare(c *gin.Context) {
	cli := initCOSClient()

	objectKey := fmt.Sprintf("wxcode/%d.png", time.Now().Unix())

	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件获取失败"})
		return
	}

	fileContent, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "文件打开失败"})
		return
	}

	authInfo, err := getTempAuthFromWX()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "Success",
			"auth":    authInfo,
			"err":     err.Error(),
		})
		return
	}

	// 上传
	_, err = cli.Object.Put(c, objectKey, fileContent, nil)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
		return
	}

	c.JSON(http.StatusInternalServerError, gin.H{
		"error":  "Failed to get WxaCode",
		"client": cli,
	})
}

func getTempAuthFromWX() (*TempAuthInfo, error) {
	// 调用微信云托管的内网 API
	resp, err := http.Get("http://api.weixin.qq.com/_/cos/getauth")
	if err != nil {
		return nil, fmt.Errorf("API 请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 解析响应
	var authInfo TempAuthInfo
	if err := json.NewDecoder(resp.Body).Decode(&authInfo); err != nil {
		return nil, fmt.Errorf("解析响应失败: %w", err)
	}

	return &authInfo, nil
}

func initCOSClient() *cos.Client {
	urlStr := fmt.Sprintf("https://%s.cos.%s.myqcloud.com", bucket, region)
	u, _ := url.Parse(urlStr)
	b := &cos.BaseURL{BucketURL: u}

	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			// 如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
			SecretID:     "SECRET_ID",
			SecretKey:    "SECRET_KEY",
			SessionToken: "SECRET_TOKEN",
		},
	})

	if client == nil {
		fmt.Printf("init client Failed!")
	}

	return client
}
